package com.igeek.shop.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.igeek.shop.entity.User;
import com.igeek.shop.service.LoginService;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		//写一个过滤器，来拦截index.jsp  和 login.jsp 。 //先判断当前请求参数是否有鞋带cookie。。。
		//cookie的形式呢  就是email = a //根据你发送过来的cookie中的用户名，查到当前用户中所有的数据，让后将查询到的结果放入到session中。
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		Cookie[] cookies = request.getCookies();
		
		if(cookies!=null){
		for(Cookie cookie : cookies){
			if(cookie.getName().equals("username")){
				String userName = cookie.getValue();
				LoginService loginService = new LoginService();
				User user = loginService.getUserByCookie(userName);
				request.getSession().setAttribute("user", user);
				
			}
		}
		}
		chain.doFilter(request, response);  //当请求放行之后 。
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	
	

	
}
